package org.example.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.apache.ibatis.annotations.*;
import org.example.entity.UserRolePlatformRelation;

import java.util.List;
import java.util.Map;

@Mapper
public interface UserRolePlatformRelationMapper extends BaseMapper<UserRolePlatformRelation> {
    
    /**
     * 根据用户ID删除所有角色关联
     */
    @Delete("DELETE FROM user_role_platform_relations WHERE user_id = #{userId}")
    int deleteByUserId(@Param("userId") Long userId);
    
    /**
     * 批量插入用户角色关联
     */
    @Insert("<script>" +
            "INSERT INTO user_role_platform_relations (user_id, role_id, is_active, created_at) VALUES " +
            "<foreach collection='roleIds' item='roleId' separator=','>" +
            "(#{userId}, #{roleId}, 1, NOW())" +
            "</foreach>" +
            "</script>")
    int batchInsert(@Param("userId") Long userId, @Param("roleIds") List<Long> roleIds);
    
    /**
     * 根据用户ID查询角色ID列表
     */
    @Select("SELECT role_id FROM user_role_platform_relations WHERE user_id = #{userId}")
    List<Long> getRoleIdsByUserId(@Param("userId") Long userId);

    /**
     * 统计各角色的用户数量
     */
    @Select("SELECT role_id, COUNT(1) AS cnt FROM user_role_platform_relations GROUP BY role_id")
    List<Map<String, Object>> countByRoleId();
    
    /**
     * 将指定角色下的用户转移到默认角色
     */
    int transferUsersToDefaultRole(@Param("oldRoleId") Long oldRoleId, @Param("defaultRoleId") Long defaultRoleId);
    
    /**
     * 将用户从旧角色转移到新角色
     */
    @Update("UPDATE user_role_platform_relations SET role_id = #{newRoleId} WHERE role_id = #{oldRoleId}")
    int transferUsersToNewRole(@Param("oldRoleId") Long oldRoleId, @Param("newRoleId") Long newRoleId);
    
    /**
     * 根据角色ID删除用户角色关联
     */
    int deleteByRoleId(@Param("roleId") Long roleId);
}
